package storage

import (
	"context"
	"fmt"

	"github.com/go-redis/redis/v9"
	"github.com/toolkits/pkg/errorx"
)

var RDB *redis.Client

type RedisConf struct {
	Host     string
	Username string
	Password string
	Port     int
	DB       int
}

func InitRedis(conf RedisConf) func() {
	RDB = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", conf.Host, conf.Port),
		Password: conf.Password, // no password set
		Username: conf.Username,
		DB:       conf.DB, // use default DB
	})

	_, err := RDB.Ping(context.Background()).Result()
	if err != nil {
		errorx.Bomb(1, "redis init fail")
	}
	return func() {
		if err := RDB.Close(); err != nil {
			errorx.Bomb(1, "redis close fail")
		}
		fmt.Printf("redis is stopped \n")
	}
}
